from datetime import datetime
from . import house_blue
from flask import render_template,jsonify,current_app,request,redirect,url_for,g
from info.utils.response_code import RET
from info.utils.response_code import error_map
from info.models import House, Area, Facility, Order
from info import db, constants
from info.utils.commons import login_required
from info.utils.image_storage import storage
import time

#首页路由映射
@house_blue.route('/')
def index():
    # return render_template('house/index.html')
    return redirect('static/html/index.html')



#返回首页轮播图
@house_blue.route('/api/v1.0/houses/index')
def get_image():
    #无参数，返回house_id,img_url,title
    try:
        house = House.query.limit(5).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='查询错误')
    #检查完整性
    if not house:
        return jsonify(errno=RET.NODATA,errmsg='查询房屋不存在')
    #定义列表返回参数
    data = []
    for item in house:
        data.append(item.to_basic_dict())

    return jsonify(errno=RET.OK,errmsg='OK',data=data)


#查询城区
@house_blue.route('/api/v1.0/areas')
def areas():
    #返回aid aname
    try:
        area = Area.query.all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='查询错误')
    if not area:
        return jsonify(errno=RET.NODATA,errmsg='数据不存在')
    data = []
    for item in area:
        data.append(item.to_dict())
    return jsonify(errno=RET.OK,errmsg='OK',data=data)


@house_blue.route('/api/v1.0/houses',methods=['GET','POST'])
@login_required
def find_house():
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg='用户未登录')
    if request.method == 'GET':
        '''
           返回查询的数据
           :return:
           '''
        # 获取请求参数,并设置默认值
        aid = request.args.get('aid', None)
        sd = request.args.get('sd', None)
        ed = request.args.get('ed', None)
        sk = request.args.get('sk', id)
        p = request.args.get('p', 1)

        # 类型转换
        try:
            p = int(p)
            if sd:
                sd = datetime.strptime(sd, "%Y-%m-%d")
            if ed:
                ed = datetime.strptime(ed, "%Y-%m-%d")
            if sd and ed:
                assert ed > sd, Exception("起始时间必须小于结束时间")
        except BaseException as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.PARAMERR, errmsg='参数错误转换')

        # 初始化过滤列表
        select_list = []
        # 按照时间查询房间
        conflict_order = None
        try:
            if sd and ed:
                conflict_order = Order.query.filter(Order.begin_date <= ed, Order.end_date >= sd).all()
            elif sd:
                conflict_order = Order.query.filter(Order.end_date >= sd).all()
            elif ed:
                conflict_order = Order.query.filter(Order.begin_date <= ed).all()
        except BaseException as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])

        # 如果存在筛选结果
        if conflict_order:
            house_id_list = [order.house_id for order in conflict_order]
            select_list.append(House.id.notin_(house_id_list))
        if aid:
            select_list.append(House.area_id == aid)
        # 查询数据
        try:
            houses = House.query.filter(*select_list)
        except BaseException as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])

        # 查询结果对象排序分页
        if sk == "booking":
            pn = houses.order_by(House.order_count.desc()).paginate(p, constants.HOME_PAGE_MAX_HOUSES)
        elif sk == "price-inc":
            pn = houses.order_by(House.price).paginate(p, constants.HOME_PAGE_MAX_HOUSES)
        elif sk == "price-des":
            pn = houses.order_by(House.price.desc()).paginate(p, constants.HOME_PAGE_MAX_HOUSES)
        else:
            pn = houses.order_by(House.create_time.desc()).paginate(p, constants.HOME_PAGE_MAX_HOUSES)

        # 编纂返回数据
        data = {
            "houses": [house.to_basic_dict() for house in pn.items],
            "total_page": pn.pages
        }
        return jsonify(errno=RET.OK, errmsg=error_map[RET.OK], data=data)



    title = request.json.get('title')
    price = request.json.get('price')
    area_id = request.json.get('area_id')
    address = request.json.get('address')
    room_count = request.json.get('room_count')
    acreage = request.json.get('acreage')
    unit = request.json.get('unit')
    capacity = request.json.get('capacity')
    beds = request.json.get('beds')
    deposit = request.json.get('deposit')
    min_days = request.json.get('min_days')
    max_days = request.json.get('max_days')
    facility = request.json.get('facility')
    
    if not all([title,price,area_id,address,room_count,acreage,unit,capacity,beds,deposit,min_days,max_days,facility]):
        return jsonify(errno=RET.PARAMERR,errmsg='参数不完整')
    try:
        area_id,room_count,acreage,capacity,min_days,max_days=int(area_id),int(room_count),int(acreage),int(capacity),int(min_days),int(max_days)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR,errmsg='数据类型错误')
    f_list = []
    try:
        for i in facility:
            f_data = Facility.query.get(i)
            if f_data:
                f_list.append(f_data)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='数据不存在')

    house = House()
    house.title=title
    house.price=price
    house.area_id=area_id
    house.address=address
    house.room_count=room_count
    house.acreage=acreage
    house.unit=unit
    house.capacity=capacity
    house.beds=beds
    house.deposit=deposit
    house.min_days=min_days
    house.max_days=max_days
    house.user_id=user.id
    house.facilities.extend(f_list)

    try:
        db.session.add(house)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR,errmsg='保存数据失败')
    house_id = house.id
    data = {
        'house_id':house_id
    }
    return jsonify(errno=RET.OK,errmsg='OK',data=data)

#上传房屋图片
@house_blue.route('/api/v1.0/houses/<int:house_id>/images',methods=['POST'])
@login_required
def house_image(house_id):
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg='用户未登录')

    house_image = request.files.get('house_image')
    # 判断参数是否存在
    if not house_image:
        return jsonify(errno=RET.PARAMERR, errmsg='参数不存在')
    # 读取图片文件
    try:
        image_data = house_image.read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg='读取图片数据失败')
    # 把读取后的图片的数据，传入七牛云
    try:
        image_name = storage(image_data)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg='上传图片异常')
    # 保存图片数据
    try:
        house = House.query.get(house_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='数据查询错误')
    if not house:
        return jsonify(errno=RET.NODATA,errmsg='数据不存在')

    house.index_image_url = image_name
    # 提交数据
    try:
        db.session.add(house)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg='保存数据失败')
    # 拼接图片的绝对路径，返回前端
    url = constants.QINIU_DOMIN_PREFIX + image_name
    data = {
        'url': url
    }
    # 返回结果
    return jsonify(errno=RET.OK, errmsg='OK', data=data)


#房屋详情
@house_blue.route('/api/v1.0/houses/<int:house_id>')
@login_required
def house_detil(house_id):
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg='用户未登录')
    try:
        house = House.query.filter(House.id == house_id).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='查询错误')
    if not house:
        return jsonify(errno=RET.NODATA,errmsg='数据不存在')
    data ={
        'house':house.to_full_dict(),
        'user_id':user.id
    }
    return jsonify(errno=RET.OK,errmsg='OK',data=data)